import React, { Component, createRef } from 'react';
import { DownOutlined, ExclamationCircleOutlined, FormOutlined, PlusOutlined, DeleteOutlined, CopyOutlined, UploadOutlined, } from '@ant-design/icons';
import { Button, Space, Dropdown, Menu, message, Modal, Popover, Switch, Select, Tooltip, Upload, } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import moment from "moment";

import { myTestList, myTestListByQuery, myTestAdd, myTestEdit, myTestDel, sysUserList} from "@/services/myTestService";

import UpdateForm from './components/UpdateForm';
import CreateForm from './components/CreateForm';

import SelectBox from "@/components/SelectBox"
import { SaveTable } from "@/utils/excelHelp"

import path from "path"
const actionRef = createRef();

class Page extends Component {
  constructor(props) {
    super(props)
    this.state = {
			SwitchisEnable: false,
      createModalVisible: false,
      updateModalVisible: false,
      selectRow: {},
      params: {},
      uploading: false,
			fuserNameOptions: [],      
    }
  
    sysUserList({
      limit: 1000,
      page: 1,
    }).then(({ result, success }) => {
      if (!success) {
        return;
      }
      const fuserNameOptions = result.arr.map(item => ({ label: item.userName, value: item.id.toString() }));
      this.setState({
        fuserNameOptions,
      })
    })
   
  }

  async handleDeal({ fields, serviceMethod, type = "操作" }) {
    const hide = message.loading("正在" + type);
    try {
      const res = await serviceMethod(fields);
      hide();
      if (!res.success) {
        message.error(type + "失败，" + res.result);
        return false;
      }
      message.success(type + "成功");
      return true;
    } catch (error) {
      hide();
      message.error(type + "异常，" + error);
      return false;
    }
  }
  async getDataSource(params) {
    const { result, success } = await myTestListByQuery({
      ...params,
			...(params["createTime"] == undefined ? {} : { ["createTime"]: params["createTime"].map(item => moment(item).format("YYYY-MM-DD HH:mm:ss")).join(",") }),      
      page: params.current,
      limit: params.pageSize,
    })
    if (!success) {
      return {
        data: [],
        page: 1,
        success: false,
        total: 0,
      };
    }
    this.setState({
      params,
    })
    return {
      data: result.arr,
      page: 1,
      success: true,
      total: result.count,
    };
  }
  createColumns() {
    return [
      {
        title: '角色名',
        dataIndex: 'roleName',
        valueType: "text",
        hideInSearch: false,
        hideInTable: false,
        hideInForm: false,
        rules: [{
          required: true,
        }],
        
      },
      {
        title: '备注',
        dataIndex: 'remark',
        valueType: "text",
        hideInSearch: false,
        hideInTable: false,
        hideInForm: false,
        rules: [{
          required: true,
        }],
        
      },
      
      {
        title: '创建时间',
        dataIndex: 'createTime',
        valueType: "date",
        render: (_, row) => moment(row["createTime"]).format("YYYY-MM-DD HH:mm"),
        hideInSearch: true,
        hideInTable: false,
        hideInForm: false,
        rules: [{
          required: true,
        }],
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        valueType: 'dateRange',
        hideInSearch: false,
        hideInTable: true,
        hideInForm: true,
      },
                {
        title: '是否可用',
        dataIndex: 'isEnable',
        hideInSearch: false,
        hideInTable: true,
        hideInForm: false,
        rules: [{
          required: true,
        }],
        valueEnum: {
          [false]: {
            text: '禁用',
            status: 'Default',
          },
          [true]: {
            text: '启用',
            status: 'Processing',
          },
        },
      },
      
      {
        title: '是否可用',
        dataIndex: 'isEnable1',
        valueType: 'option',
        render: (_, row) => {
          return (<Switch disabled={this.state.SwitchisEnable}
            checkedChildren={"可用"} unCheckedChildren={"禁用"}
            onChange={async (val) => {
              const success = await this.handleDeal({
                type: "操作",
                fields: {
                  ["id"]: row["id"],
                  ["isEnable"]: val,
                },
                serviceMethod: myTestEdit,
              });
              if (!success) {
                return;
              }
              if (!actionRef.current) {
                return;
              }
              actionRef.current.reload();
            }}
            checked={row["isEnable"]}
          // defaultChecked={_}
          />)
        }
      },
      
                
      {
        title: '创建者',
        dataIndex: 'createBy',
        hideInTable: true,
        hideInSearch: true,
        renderFormItem: (item, { defaultRender, ...rest }, form) => {
          return (<Select showSearch options={this.state.fuserNameOptions} filterOption={(input, option) => option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0} />)
        },
        rules: [{
          required: true,
        }],
      },
      {
        title: '创建者',
        dataIndex: 'fuserName',
        valueType: "text",
        hideInSearch: false,
        hideInTable: false,
        hideInForm: true,
      },
      
      
   {
        title: '操作',
        dataIndex: 'option',
        valueType: 'option',
        render: (_, row) => (
          <Space>
          
          <Tooltip title="复制这条信息">
          <Button
              title="复制"
              onClick={(e) => {
                e.stopPropagation();
                Modal.confirm({
                  title: '是否确认复制该条信息?',
                  icon: <ExclamationCircleOutlined />,
                  onOk: async () => {
                    const success = await this.handleDeal({
                      type: "复制",
                      fields: row,
                      serviceMethod: myTestAdd,
                    });
                    if (!success) {
                      return;
                    }
                    this.setState({
                      createModalVisible: false,
                    })
                    if (!actionRef.current) {
                      return;
                    }
                    actionRef.current.reload();
                  },
                });

              }}
              size="small" type="default" icon={<CopyOutlined />}></Button>
            </Tooltip>
          
          
          <Tooltip title="编辑">
          <Button
              onClick={async (e) => {
                e.stopPropagation();
                const selectRow = {
                  ...row,
									...(row["isEnable"] == undefined ? {} : { ["isEnable"]: row["isEnable"].toString() }),
									...(row["createBy"] == undefined ? {} : { ["createBy"]: row["createBy"].toString() }),
									...(row["createTime"] == undefined ? {} : { ["createTime"]: moment(row["createTime"]) }),
                }
                this.setState({
                  updateModalVisible: true,
                  selectRow,
                })
              }}
              size="small" type="primary" icon={<FormOutlined />} ></Button>
          </Tooltip>
          
              
            <Tooltip title="删除">
              <Button
              style={{marginRight:5}}
              onClick={(e) => {
                e.stopPropagation();
                Modal.confirm({
                  title: '是否确认删除?',
                  icon: <ExclamationCircleOutlined />,
                  onOk: async () => {
                    const idList = {
                      id: [
                        row["id"]
                      ]
                    };
                    const success = await this.handleDeal({
                      type: "删除",
                      fields: idList,
                      serviceMethod: myTestDel
                    });
                    if (!success) {
                      return;
                    }
                    if (!actionRef.current) {
                      return;
                    }
                    actionRef.current.reload();
                  },
                });
              }}
              size="small" type="primary" icon={<DeleteOutlined />}></Button>
          </Tooltip>
              
            
          </Space>
        ),
      },
      
   
    ];
  }
  getArr() {
    const columns = this.createColumns().filter(item => item.valueType != "option");
    const ARR = [...new Set(columns.map(item => item.dataIndex))].map(item => {
      const obj = columns.find(sitem => sitem.dataIndex == item);
      return {
        label: obj.title,
        value: obj.dataIndex,
      }
    })
    return ARR;
  }
  render() {
    
    const importProps = {
      showUploadList: false,
      name: 'file',
      action: '/api/myTest/importExcel',
      headers: { auth: localStorage.getItem("authInfo") },
      data: {
        jsonStr: JSON.stringify(this.getArr()),
      },
      onChange: (info) => {
        if (info.file.status === 'uploading') {
          this.setState({
            uploading: true,
          });
          return;
        }
        if (info.file.status === 'done') {
          if (info.file.response.success) {
            message.success(info.file.name + " 导入成功！");
            if (!actionRef.current) {
              return;
            }
            actionRef.current.reload();
          }
          else {
            message.error("执行出错！" + info.file.response.result);
          }
          this.setState({
            uploading: false,
          });
        } else if (info.file.status === 'error') {
          this.setState({
            uploading: false,
          });
          message.error(info.file.name + " 上传文件时发生错误！");
        }
      },
      beforeUpload(file) {
        const maxSize = 10;
        const fileEx = path.extname(file.name).toLowerCase();
        if (!(fileEx == ".xls" || fileEx == ".xlsx")) {
          message.error('仅仅支持 Excel 文件! 后缀名为：.xls .xlsx');
          return false;
        }
        const isLt2M = file.size / 1024 / 1024 < maxSize;
        if (!isLt2M) {
          message.error("图片必须小于 " + maxSize + "MB!");
        }
        return isLt2M;
      },
      accept: ".xls,.xlsx",
    };
    
    return (
      <PageHeaderWrapper>
        <ProTable
          actionRef={actionRef}
          headerTitle={""}
          rowKey="id"
          params={{}}
          request={async (params) => this.getDataSource(params)}
          columns={this.createColumns()}
          rowSelection={{}}
          pagination={{
            pageSize: 10,
          }}
          search={true}
          toolBarRender={(action, { selectedRowKeys, selectedRows }) => {
            return ([
              
              <Popover
                content={
                  <div style={{ padding: "12px 10px" }}>
                    <div style={{ padding: "10px 30px" }}>请以 “导出” 的文件为模板导入</div>
                    <div style={{ textAlign: "right", marginTop: 15 }}>
                      <Upload  {...importProps}>
                        <Button type="primary" loading={this.state.uploading} icon={<UploadOutlined />}>上传EXCEL文件</Button>
                      </Upload>
                    </div>
                  </div>
                }
                title="导入数据"
                trigger="click">
                <Button type="dashed">导入</Button>
              </Popover>,
              
                
              <Popover
                content={
                  <SelectBox
                    Submit={async (arr) => {
                      const res = await myTestListByQuery({
                        ...this.state.params,
                        page: 1,
                        limit: 10000,
                      })
                      if (!res.success) {
                        message.error("操作失败，" + res.result);
                        return;
                      }
                      let mapping = {};
                      arr.forEach(ele => {
                        mapping[ele.value] = ele.label;
                      })
                      SaveTable({
                        arr: res.result.arr,
                        mapping,
                        isOrder:false,
                      })
                    }}
                    arr={this.getArr()} />}
                title="选择要导出的字段"
                trigger="click">
                <Button type="dashed">导出</Button>
              </Popover>,
                
             <Button type="primary" onClick={() => {
                const selectRow = {}
                this.setState({
                  createModalVisible: true,
                  selectRow,
                })
              }}>
                <PlusOutlined /> 新建
                          </Button>,
             
              selectedRowKeys && selectedRowKeys.length > 0 && (
                <Dropdown
                  overlay={
                    <Menu
                      onClick={async e => {
                        
                        if (e.key === 'remove') {
                          const idList = {
                            id: selectedRowKeys
                          };
                          Modal.confirm({
                            title: '是否确认删除?',
                            icon: <ExclamationCircleOutlined />,
                            onOk: async () => {
                              const success = await this.handleDeal({
                                type: "删除",
                                fields: idList,
                                serviceMethod: myTestDel
                              });
                              if (!success) {
                                return;
                              }
                              if (!actionRef.current) {
                                return;
                              }
                              actionRef.current.reload();
                            },
                          });
                        }
                        
                      }}
                      selectedKeys={[]}
                    >
                    <Menu.Item key="remove">批量删除</Menu.Item>
                      
                    </Menu>
                  }
                >
                  <Button>
                    批量操作 <DownOutlined />
                  </Button>
                </Dropdown>
              ),
            ]);
          }}
        />
        
        <CreateForm
          onCancel={() => this.setState({ createModalVisible: false })}
          createModalVisible={this.state.createModalVisible}
        >
          <ProTable
            onSubmit={async fieldsValues => {
              const fields = {
                ...fieldsValues,
								...(fieldsValues["createBy"] == undefined ? {} : { ["createBy"]: Number(fieldsValues["createBy"]) }),
								...(fieldsValues["isEnable"] == undefined ? {} : { ["isEnable"]: fieldsValues["isEnable"] == "true" }),                
              }
              const success = await this.handleDeal({
                type: "添加",
                fields,
                serviceMethod: myTestAdd,
              });
              if (!success) {
                return;
              }
              this.setState({
                createModalVisible: false,
              })
              if (!actionRef.current) {
                return;
              }
              actionRef.current.reload();
            }}
            rowKey="id"
            type="form"
            form={{
              initialValues: {
                ...this.state.selectRow,
              }
            }}
            columns={this.createColumns()}
          />
        </CreateForm>
        
        
        <UpdateForm
          onCancel={() => this.setState({ updateModalVisible: false })}
          updateModalVisible={this.state.updateModalVisible}
        >
          <ProTable
            onSubmit={async fieldsValues => {
              const fields = {
                ...fieldsValues,
								...(fieldsValues["createBy"] == undefined ? {} : { ["createBy"]: Number(fieldsValues["createBy"]) }),
								...(fieldsValues["isEnable"] == undefined ? {} : { ["isEnable"]: fieldsValues["isEnable"] == "true" }),   
                ["id"]: this.state.selectRow["id"],
              }
              const success = await this.handleDeal({
                type: "更新",
                fields,
                serviceMethod: myTestEdit,
              });
              if (!success) {
                return;
              }
              this.setState({
                updateModalVisible: false,
              })
              if (!actionRef.current) {
                return;
              }
              actionRef.current.reload();
            }}
            rowKey="id"
            type="form"
            form={{
              initialValues: {
                ...this.state.selectRow,
              }
            }}
            columns={this.createColumns()}
          />
        </UpdateForm>
        
      </PageHeaderWrapper>
    )
  }
}
export default Page    
